package com.homwee.factory.tvtool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.homwee.factory.R;
import com.mediatek.twoworlds.factory.MtkTvFApiDisplay;
import com.mediatek.twoworlds.factory.MtkTvFApiInputSource;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.factory.clientwrapper.MtkTvFApiInformationWrapper;
import com.mediatek.twoworlds.factory.common.MtkTvFApiDisplayTypes.EnumInputSourceType;
import com.mediatek.twoworlds.factory.common.MtkTvFApiDisplayTypes.EnumOverScanScreenMode;
import com.mediatek.twoworlds.factory.common.MtkTvFApiDisplayTypes.EnumOverScanTiming;
import com.mediatek.twoworlds.factory.common.inimanager.MtkTvFApiDisplayIniManager;
import com.mediatek.twoworlds.tv.MtkTvAVMode;
import com.mediatek.twoworlds.tv.MtkTvBanner;
import com.mediatek.twoworlds.tv.MtkTvBroadcast;
import com.mediatek.twoworlds.tv.MtkTvInputSource;
import com.mediatek.twoworlds.tv.model.MtkTvScreenModeOverscan;
import com.mediatek.twoworlds.factory.common.MtkTvFApiResultTypeBase;


import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.storage.StorageManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


import com.homwee.factory.TvToolService;
import com.homwee.factory.tvtool.INIFile;
import com.homwee.factory.util.Contants;

//import com.changhong.dm.DeviceManager;
//import com.changhong.dm.MountPoint;
//import com.changhong.tvos.common.TVManager;
//import com.changhong.tvos.common.exception.IllegalValueException;
//import com.changhong.tvos.common.exception.TVManagerNotInitException;
//import com.changhong.tvos.model.ChOsType.ENUMOverScanMode;
//import com.changhong.tvos.model.ENUMPlayerScenes;

public class ReproductionService extends Service {

	WindowManager mWindowManager;
	LayoutInflater mInflater;
	private long mExitTime;
	WindowManager.LayoutParams wmParams_reproduction;
	LinearLayout mLayout;
	EnumInputSourceType currentSource;
	EnumOverScanTiming currentTiming;
	EnumOverScanScreenMode currentScreenMode = EnumOverScanScreenMode.E_MTK_FAPI_OVERSCAN_SCREEN_MODE_AUTO;
	int curSourceType;
	EnumOverScanTiming curTiming;
	int curScreenMode;
	
	
    //DeviceManager mDeviceManager = DeviceManager.getInstance();
    //ArrayList<MountPoint> deviceLabel = mDeviceManager.getMountPointList();    		
	String SDPath;
	
	
	@Override
	public void onCreate() { 
		// TODO Auto-generated method stub
		mWindowManager = (WindowManager) getApplication().getSystemService(
				getApplication().WINDOW_SERVICE);
		mInflater = LayoutInflater.from(getApplication());
		
		
		
	
		
		
		checkSDCardSwitchOn();

		createReproductionView();
		mWindowManager.addView(mLayout, wmParams_reproduction);
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		if (mLayout != null) {
			// mWindowManager.removeView(mTabHost_pq);
		}
		if (timer != null) {
			timer.cancel();
		}
		Intent i = new Intent(getApplicationContext(), TvToolService.class);
		startService(i);
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	protected void OpenTipDialog(String strTitle, String strInfo) {
		Toast.makeText(this, strTitle + ": " + strInfo, Toast.LENGTH_SHORT)
				.show();
	}

	protected boolean checkSDCardSwitchOn() {
		// TODO Auto-generated method stub
//        if (deviceLabel.size() ==1){
//        	Log.i(TAG, "U disk was not found");
//        	return false;
//        }else{
//        	Log.i(TAG, "U disk was found");
//        	SDPath = deviceLabel.get(1).mMountPoint;
//        	Log.i(TAG, "SDPath = " + SDPath);
//	        for (int i = 0; i < deviceLabel.size(); i++) {
//	  		    Log.i(TAG, "mMountPoint: " + deviceLabel.get(i).mMountPoint);
//	  		}        	
//        	return true;
//        } 
		
		try {
			StorageManager mStorageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
			Class<?>[] paramClasses = {};
			Object[] params = {};
			Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", paramClasses);
			String[] paths = (String[]) getVolumePathsMethod.invoke(mStorageManager, params);		
			int size = 0;
			for(String str:paths){
				 Log.i(TAG,"myprint:"+str); 
				 size++;
		  	}
			
			if(size<=1){
				Log.i(TAG, "U disk was not found");
				return false;
			}else{
				SDPath = paths[1];
				Log.i(TAG, "U disk was found");
				Log.i(TAG, "SDPath = " + SDPath);
				return true;			
			     }			
			
		} catch (Exception e) {
		    Log.e(TAG, "CheckSDCardSwitchOn() failed", e);
		    return false;
		}
		
		
		
		
		
		
	}

	private void createReproductionView() {
		wmParams_reproduction = new WindowManager.LayoutParams();
		wmParams_reproduction.type = LayoutParams.TYPE_PHONE;
		wmParams_reproduction.format = PixelFormat.RGBA_8888;
		wmParams_reproduction.gravity = Gravity.CENTER;
		wmParams_reproduction.x = 0;
		wmParams_reproduction.y = 0;
		wmParams_reproduction.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams_reproduction.height = WindowManager.LayoutParams.WRAP_CONTENT;
		mLayout = new ReproductionLayout(getApplicationContext(), this);

		sb_top = (SeekBar) mLayout.findViewById(R.id.seekBar_top);
		sb_bottom = (SeekBar) mLayout.findViewById(R.id.seekBar_bottom);
		sb_left = (SeekBar) mLayout.findViewById(R.id.seekBar_left);
		sb_right = (SeekBar) mLayout.findViewById(R.id.seekBar_right);
		sb_top.setMax(100);
		sb_bottom.setMax(100);
		sb_left.setMax(100);
		sb_right.setMax(100);

		sb_top.setKeyProgressIncrement(seekBarStep);
		sb_bottom.setKeyProgressIncrement(seekBarStep);
		sb_left.setKeyProgressIncrement(seekBarStep);
		sb_right.setKeyProgressIncrement(seekBarStep);

		tv_top = (TextView) mLayout.findViewById(R.id.reproduction_top_value);
		tv_bottom = (TextView) mLayout
				.findViewById(R.id.reproduction_bottom_value);
		tv_left = (TextView) mLayout.findViewById(R.id.reproduction_left_value);
		tv_right = (TextView) mLayout
				.findViewById(R.id.reproduction_right_value);

		bt_refresh = (Button) mLayout.findViewById(R.id.refresh_reproduction);
		bt_refresh.setText(getString(R.string.Reproduction_reset));
		bt_refresh.setOnClickListener(listener_btRefresh);
		bt_refresh.requestFocus();

		tv_panelName = (TextView) mLayout.findViewById(R.id.tv_panelName);
		getProductName();// Gets the current screen name

		if (checkIniFileExists())// Check if the INI file already exists
		{
//			if (!readIniFile())// Read the INI file data to the overScanValues array
//			{
//				Toast.makeText(getApplicationContext(), "An error occurred reading the configuration file閿涘verScanValues all set for 0", Toast.LENGTH_LONG).show();
//				for (int i = 0; i < overScanNames.length; i++) {
//					for (int j = 0; j < 4; j++) {
//						overScanValues[i][j] = 0;
//					}
//				}
//			}

		} else {
			AlertIniFileAbsence();
			// createNewIniFile();
		}

		curIndex = getCurIndex();

		tv_indexName = (TextView) mLayout.findViewById(R.id.tv_indexName);
		tv_indexName.setText(MtkTvInputSource.getInstance().getCurrentInputSourceName()+" "+MtkTvBanner.getInstance().getVideoInfo());//overScanNames[curIndex]);

		curRect = getCurValues(curIndex);// Sets the four value of the curRect based on the Index value

		setReproductionRateValue(); // Setting UI interface data
		tv_top.setText("" + curRect.top);
		tv_bottom.setText("" + curRect.bottom);
		tv_left.setText("" + curRect.left);
		tv_right.setText("" + curRect.right);
		inittop = curRect.top;
		initbottom = curRect.bottom;
		initleft = curRect.left;
		initright = curRect.right;

		sb_top.setOnSeekBarChangeListener(listener_seekBar);
		sb_bottom.setOnSeekBarChangeListener(listener_seekBar);
		sb_left.setOnSeekBarChangeListener(listener_seekBar);
		sb_right.setOnSeekBarChangeListener(listener_seekBar);

		bt_exit = (Button) mLayout.findViewById(R.id.bt_exit);
		bt_exit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mWindowManager.removeView(mLayout);
				Intent mainIntent = new Intent(ReproductionService.this,
						TvToolService.class);
				startService(mainIntent);
				stopSelf();
			}

		});

		bt_save = (Button) mLayout.findViewById(R.id.bt_save);
		bt_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				saveOverScanValues("save");// Writes the data in the overScanValues array to the INI file
			}
		});

		bt_export = (Button) mLayout.findViewById(R.id.bt_export);
		bt_export.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (checkSDCardSwitchOn()) {
//					saveOverScanValues(localIniFilePath);
					saveOverScanValues("export");
				} else {
					AlertSDCardAbsence();
				}

			}
		});

		if (!checkSignalStable()) {
			Toast.makeText(getApplicationContext(), "No Signal !",
					Toast.LENGTH_LONG).show();
			enableViews(false);
			tv_indexName.setText("   No Signal");
		}
		startIndexMonitor();// Use timer to detect Index changes periodically

	}

	private void enableViews(boolean enabled) {
		// TODO Auto-generated method stub
		try {
			sb_top.setEnabled(enabled);
			sb_bottom.setEnabled(enabled);
			sb_left.setEnabled(enabled);
			sb_right.setEnabled(enabled);
			bt_refresh.setEnabled(enabled);
			bt_save.setEnabled(enabled);
			bt_export.setEnabled(enabled);
		} catch (Exception e) {
			e.printStackTrace();
			Log.v("TVtool", "enableViews wrong !");
		}
	}

	private boolean checkSignalStable() {
		// TODO Auto-generated method stub
		boolean retValue = true;
		try {
			
			retValue = MtkTvBroadcast.getInstance().isSignalLoss();//true;//mTvChannelManager.isSignalStabled();
//			retValue = TVManager.getInstance(ReproductionService.this)
//					.getTVPlayer().isSignalStable();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "get signal wrong !",
					Toast.LENGTH_LONG).show();
			retValue = false;
		}

		bSignal = !retValue;
		return !retValue;
	}

	private void createNewIniFile() {
		// TODO Auto-generated method stub
		try {
			File panel_ini = new File(localIniFilePath);
			INIFile iniFile = new INIFile("Reproduction", productName);
			panel_ini.createNewFile();

			iniFile.SetValue("Version", "Overscan_Version", "1.01");
			String tmpStr;
			for (int i = 0; i < overScanNames.length; i++) {
				tmpStr = "{" + overScanValues[i][0] + ","
						+ overScanValues[i][1] + "," + overScanValues[i][2]
						+ "," + overScanValues[i][3] + "}";
				iniFile.SetValue("OverScan_Array", overScanNames[i], tmpStr);
			}
			if (iniFile.closeINI(localIniFilePath)) {
				Toast.makeText(getApplicationContext(), getString(R.string.reproduct_config_file_success),
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(getApplicationContext(), getString(R.string.reproduct_config_file_fail),
						Toast.LENGTH_LONG).show();
			}

		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Configuration file creation failed锛�",
					Toast.LENGTH_LONG).show();
		}

	}

	protected void AlertSDCardAbsence() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "Please plug in the SDcard or U disk first锛�",
				Toast.LENGTH_LONG).show();
	}

	Timer timer;
	TimerTask timerTask;
	Handler handler;

	private boolean IsUsbPlayScenes(){	
		
		String currentSource =MtkTvInputSource.INPUT_TYPE_ATV;//EnumInputSource.E_INPUT_SOURCE_ATV;
		boolean SignalStable = false;
		try {
			currentSource = MtkTvInputSource.getInstance().getCurrentInputSourceName();//mTvCommonManager.getCurrentInputSource();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		try {
			//less of MTK		
			SignalStable=MtkTvBroadcast.getInstance().isSignalLoss();//mTvChannelManager.isSignalStabled();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
			SignalStable = false;
		}
		
		
//		if ((currentSource ==EnumInputSource.E_INPUT_SOURCE_STORAGE ||
//			 currentSource ==EnumInputSource.E_INPUT_SOURCE_STORAGE2)&&SignalStable){
//			
//			return true;
//			
//		}else{
			return false;
//		}
			
		
		
	}
	private void startIndexMonitor() {
		// TODO Auto-generated method stub
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				if(bUSBMode)
				{
					//if(getInputSource() != ENUMPlayerScenes.EN_PLAYER_SCENES_MMP)
					if(!IsUsbPlayScenes())
					{
						bUSBMode = false;
						enableViews(true);
						refreshUI(getCurIndex());
					}
				}
				else
				{
					//if(getInputSource() == ENUMPlayerScenes.EN_PLAYER_SCENES_MMP)
					if(IsUsbPlayScenes())
					{
						bUSBMode = true;
						enableViews(true);
//						tv_indexName.setText("USB涓嬪悓HDMI");
						refreshUI(getCurIndex());
						return;
					}
				}
				
				
				if (bOverScanModeHigh) {
					//less of MTK
//					if (getOverScanMode() == ENUMOverScanMode.CH_OVERSCAN_MODE_STANDARD) {//Standards are set out by tools
//						bOverScanModeHigh = false;
//						enableViews(true);
//						refreshUI(getCurIndex());
//					}
//				} else {
//					if (getOverScanMode() == ENUMOverScanMode.CH_OVERSCAN_MODE_HIGH) {// All show, not adjustable
//						bOverScanModeHigh = true;
//						enableViews(false);
//						tv_indexName.setText("The rate of repetition rate is high锛宱nly standard mode can be adjusted");
//						return;
//					}
				}

				if (!bSignal) {
					if (checkSignalStable()) {
						enableViews(true);
						refreshUI(getCurIndex());
					}
				}

				if (!checkSignalStable()) {
					enableViews(false);
					tv_indexName.setText("   No Signal");
					// timer.cancel();
					return;
				}

				getProductName();

				int idx = getCurIndex();
				if (curIndex != idx) {
					AlertIndexChanged();
					curIndex = getCurIndex();
					refreshUI(curIndex);
				}
			}

		};
		timerTask = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(0);
			}

		};
		timer = new Timer();
		timer.schedule(timerTask, 0, 3000);
	}

	protected void AlertIndexChanged() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "The format has been detected", Toast.LENGTH_LONG)
				.show();
	}

	protected void refreshUI(int idx) {
		// TODO Auto-generated method stub
		getCurValues(idx);
//		curRect.top = overScanValues[idx][0];
//		curRect.bottom = overScanValues[idx][1];
//		curRect.left = overScanValues[idx][2];
//		curRect.right = overScanValues[idx][3];
		setReproductionRateValue();
		tv_indexName.setText(MtkTvInputSource.getInstance().getCurrentInputSourceName()+" "+MtkTvBanner.getInstance().getVideoInfo());
	}
	protected void resetUI() {
		// TODO Auto-generated method stub
		curRect.top = inittop;
		curRect.bottom=initbottom ;
		curRect.left=initleft;
		curRect.right = initright;
		Log.v(TAG, "resetUI curRect.top="+curRect.top+" curRect.bottom="+curRect.bottom+" curRect.left="+curRect.left+" curRect.right="+curRect.right);
		MtkTvFApiDisplay.getInstance().setOverScan(EnumInputSourceType.values()[curSourceType], MtkTvAVMode.getInstance().getCrntOverscan().getTimingIdx(),EnumOverScanScreenMode.values()[curScreenMode], curRect.left, curRect.right, curRect.top, curRect.bottom);
		MtkTvAVMode.getInstance().setCrntOverscan(curRect.top, curRect.bottom, curRect.left, curRect.right);
		MtkTvAVMode.getInstance().updateOverscanIni();

//		curRect.top = overScanValues[idx][0];
//		curRect.bottom = overScanValues[idx][1];
//		curRect.left = overScanValues[idx][2];
//		curRect.right = overScanValues[idx][3];
		setReproductionRateValue();
		tv_indexName.setText(MtkTvInputSource.getInstance().getCurrentInputSourceName()+" "+MtkTvBanner.getInstance().getVideoInfo());
	}


	protected int updateformat(){
		if(!MtkTvFApiSystem.getInstance().isFileExist(sdcardIniFilePath)) {
			MtkTvFApiSystem.getInstance().copyFile(localIniFilePath,
        			sdcardIniFilePath,
    				 false);
		}
		int ret = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK;
		String IniPath = sdcardIniFilePath;
		ret = MtkTvFApiInformationWrapper.getInstance().openIniFile(IniPath);
        if( ret != MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK )
        {
        	Log.v(TAG, "openIniFile Fail, result = " + ret);
            return ret;
        }
        int iniDataSize = 140;
		String Key =  MtkTvFApiDisplayIniManager.getInstance().getKey(MtkTvFApiDisplayIniManager.MTKTV_FAPI_KEY_TYPE_DISPLAY_ENUM.E_MTK_FAPI_KEY_TYPE_ATV_OVERSCAN_SIG_NTSC.ordinal());
		for(int keyIndex=MtkTvFApiDisplayIniManager.MTKTV_FAPI_KEY_TYPE_DISPLAY_ENUM.E_MTK_FAPI_KEY_TYPE_ATV_OVERSCAN_SIG_NTSC.ordinal();
				keyIndex<MtkTvFApiDisplayIniManager.MTKTV_FAPI_KEY_TYPE_DISPLAY_ENUM.E_MTK_FAPI_KEY_TYPE_VD_OVERSCAN_SIG_PAL_NC.ordinal();
				keyIndex++) {
			Key =  MtkTvFApiDisplayIniManager.getInstance().getKey(keyIndex);
			String iniData = MtkTvFApiInformationWrapper.getInstance().readIniFile(Key);
	        String []data = new String[iniDataSize];
	        String []split_line = iniData.split(",");
	        int index = 0;
	        for (String s: split_line) {
	            data[index++] = s;
	            if(index > iniDataSize - 1) {
	            	Log.v(TAG, "Overflow");
	            	MtkTvFApiInformationWrapper.getInstance().saveIniFile(IniPath);
	            	return MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_FAIL;
	            }
	        }


	        String setIniData = "";
	        int i;
	        for (i = 0; i < index; i++) {
	        	if(i==0) {
	        		setIniData += ("\\\n"+data[i]+",");
	        	}else if(i == index -1 ) {
	                setIniData += (data[i]+";\n");
	            }else if((i+1)%6 == 0){
	            	setIniData += (data[i]+",\\\n");
	            }else
	                setIniData += (data[i]+",");
	        }
	        ret = MtkTvFApiInformationWrapper.getInstance().writeIniFile(Key, setIniData);
	        
	        if( ret != MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK )
	        {
	        	Log.v(TAG, "writeIniFile Fail, result = " + ret);
	        	return MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_FAIL;
	        }
		}
		ret = MtkTvFApiInformationWrapper.getInstance().saveIniFile(IniPath);
		 Log.v(TAG, "updateformat, result = " + ret);

	    return ret;
	}

	protected void saveOverScanValues(String type) {
		// TODO Auto-generated method stub
		// File file = new File(filePath);
//		File file_test = new File("/data/test.ini");
//		
//		try {
//			file_test.createNewFile();
//			FileOutputStream outStream = new FileOutputStream(file_test);
//			byte[] buffer = new byte[10];
//			buffer[0] = 0;
//			buffer[1] = 5;
//			outStream.write(buffer);
//			outStream.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		MtkTvAVMode.getInstance().updateOverscanIni();
//		MtkTvFApiDisplayIniManager.getInstance().saveIni();
		
		inittop = curRect.top;
		initbottom = curRect.bottom;
		initleft = curRect.left;
		initright = curRect.right;

		MtkTvFApiDisplay.getInstance().saveDisplayIni();
        MtkTvAVMode.getInstance().updateOverscanIni();
        if(type.endsWith("export")) {
        	if(SDPath == null || SDPath.isEmpty()) {
        		Toast.makeText(getApplicationContext(), "U disk not found!!!", Toast.LENGTH_LONG)
    			.show();
        	}else {
        		int ret = MtkTvFApiSystem.getInstance().copyFile(localIniFilePath,
            			sdcardIniFilePath,
        				 false);
        		if(ret == 0) {
        			updateformat();
            	    Toast.makeText(getApplicationContext(), "export successed!", Toast.LENGTH_LONG)
            			.show();
                }
        	}
        	
        }else {
        	Toast.makeText(getApplicationContext(), "saved successed!", Toast.LENGTH_LONG)
			.show();
        }
        
//		MtkTvAVMode.getInstance().updateOverscanIni();
//		INIFile iniFile = new INIFile("Reproduction", productName);
//		String tmpStr;
//		iniFile.SetValue("Version", "Overscan_Version", "1.01");
//		for (int i = 0; i < overScanNames.length; i++) {
//			tmpStr = "{" + overScanValues[i][0] + "," + overScanValues[i][1]
//					+ "," + overScanValues[i][2] + "," + overScanValues[i][3]
//					+ "}";
//			iniFile.SetValue("OverScan_Array", overScanNames[i], tmpStr);
//		}
//		if (iniFile.closeINI(filePath)) {
//			Toast.makeText(getApplicationContext(), getString(R.string.reproduct_save_success) + filePath,
//					Toast.LENGTH_LONG).show();
//		} else {
//			Toast.makeText(getApplicationContext(), getString(R.string.reproduct_save_fail) + filePath,
//					Toast.LENGTH_LONG).show();
//		}

	}

	private Rect getCurValues(int idx) {
		// TODO Auto-generated method stub
		MtkTvAVMode.getInstance().updateOverscanIni();
		MtkTvScreenModeOverscan overscan = MtkTvAVMode.getInstance().getCrntOverscan();
		Rect retRect = new Rect();
		if(overscan != null){
		retRect.top = overscan.getTop();
		retRect.bottom = overscan.getBottom();
		retRect.left = overscan.getLeft();
		retRect.right = overscan.getRight();
		}
		return retRect;
	}

	private void AlertCurIndexAbsence() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), getString(R.string.reproduct_get_index_fail),
				Toast.LENGTH_LONG).show();
	}

//	private ENUMPlayerScenes getInputSource() {
//		ENUMPlayerScenes playerScene = ENUMPlayerScenes.EN_PLAYER_SCENES_ATV;
//			try {
//				playerScene = TVManager.getInstance(ReproductionService.this).getTVPlayer().getCurrentPlayerScenes();
////				Toast.makeText(getApplicationContext(), "褰撳墠杈撳叆锛�"+playerScene.toString(), Toast.LENGTH_SHORT).show();
//			} catch (TVManagerNotInitException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				Toast.makeText(getApplicationContext(), "鑾峰彇杈撳叆鍦烘櫙澶辫触!", Toast.LENGTH_LONG).show();
//			}			
//		return playerScene;
//	}

	//less of MTK
//	private ENUMOverScanMode getOverScanMode() {
//		ENUMOverScanMode mode = ENUMOverScanMode.CH_OVERSCAN_MODE_STANDARD;
//		try {
//			mode=mTvMiscManager.getOverScanMode();
////			mode = TVManager.getInstance(ReproductionService.this)
////					.getPictureManager().getOverScanMode();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//		return mode;
//	}

	private int getCurIndex() {
		// TODO Auto-generated method stub
		int idx = -1;
		try {
			//less of MTK
//			idx = mTvMiscManager.getToolCurOverScanTimingIndex();
//			idx = TVManager.getInstance(ReproductionService.this)
//					.getPictureManager().getToolCurOverScanTimingIndex();
			// Toast.makeText(getApplicationContext(), "" + idx ,
			// Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.v("TVtool", "getCurIndex wrong!");
			AlertCurIndexAbsence();
		}
//		if (idx < 0 || idx >= overScanNames.length) {
//			Log.e("TVtool", "getCurIndex idx wrong!");
//			idx = 0;
//			AlertCurIndexAbsence();
//		}
		return idx;
	}

	private void AlertIniFileAbsence() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(),
				getString(R.string.reproduct_cannot_get_config_file), Toast.LENGTH_LONG).show();
	}

	/*
	 * Read the INI file data to the overScanValues array
	 */
	private boolean readIniFile() {
		// TODO Auto-generated method stub
		try {
			INIFile iniFile = new INIFile("Reproduction", productName);
			int readLines = iniFile.openINI(localIniFilePath);
			
/*			Toast.makeText(getApplicationContext(), "鎵撳紑" + localIniFilePath + "瀹屾垚,璇诲彇鍒�" + readLines + "琛�",
					Toast.LENGTH_LONG).show();*/
			String tmpStr = "";
			Rect tmpRect = null;
			for (int i = 0; i < overScanNames.length; i++) {
				tmpStr = iniFile.GetValue("OverScan_Array", overScanNames[i]);
/*				Toast.makeText(getApplicationContext(), "璇诲彇瀛楁 [OverScan_Array]" +overScanNames[i] +"鐨勫�间负\"" + tmpStr + "\"",
						Toast.LENGTH_LONG).show();
				Toast.makeText(getApplicationContext(), "鍑嗗鎷嗗垎璇ュ��", Toast.LENGTH_LONG).show();*/
				tmpRect = getRectFromString(tmpStr);

				if (tmpRect == null) {
					Toast.makeText(getApplicationContext(), getString(R.string.reproduct_divide_fail), Toast.LENGTH_LONG).show();
					return false;
				}
/*				Toast.makeText(getApplicationContext(), "鎷嗗垎缁撴灉-top:" + tmpRect.top + "bottom:" + tmpRect.bottom + "left:" + tmpRect.left + "right:" + tmpRect.right,
						Toast.LENGTH_LONG).show();
				Toast.makeText(getApplicationContext(), "ready to setOverScanValues", Toast.LENGTH_LONG).show();*/
				setOverScanValues(i, tmpRect);
/*				Toast.makeText(getApplicationContext(), "setOverScanValues success锛�",
						Toast.LENGTH_LONG).show();*/
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			Log.v("TVtool", "readIniFile failed!");
			Toast.makeText(getApplicationContext(), getString(R.string.reproduct_read_config_fail)+e.toString(),
					Toast.LENGTH_LONG).show();
/*			SimpleAlertDialog dialog = new SimpleAlertDialog(ReproductionService.this,null);
			dialog.setMessage(e.toString());
			dialog.show();*/
			return false;
		}

	}

	private void setOverScanValues(int idx, Rect tmpRect) {
		// TODO Auto-generated method stub
//		overScanValues[idx][0] = tmpRect.top;
//		overScanValues[idx][1] = tmpRect.bottom;
//		overScanValues[idx][2] = tmpRect.left;
//		overScanValues[idx][3] = tmpRect.right;
		MtkTvFApiDisplay.getInstance().setOverScan(EnumInputSourceType.values()[curSourceType], MtkTvAVMode.getInstance().getCrntOverscan().getTimingIdx(),EnumOverScanScreenMode.values()[curScreenMode], tmpRect.left, tmpRect.right, tmpRect.top, tmpRect.bottom);
		MtkTvAVMode.getInstance().setCrntOverscan(tmpRect.top, tmpRect.bottom, tmpRect.left, tmpRect.right);
	}

	private Rect getRectFromString(String valueStr) {
		// TODO Auto-generated method stub
		String tmpStr = valueStr.trim();
		if (!tmpStr.startsWith("{") || !tmpStr.endsWith("}")) {
			Toast.makeText(getApplicationContext(), getString(R.string.reproduct_format_error1),
					Toast.LENGTH_LONG).show();
			return null;
		}

		Rect rect = new Rect();
		try {
			String[] values = tmpStr.replace("{", "").replace("}", "")
					.split(",");
			if(values.length != 4)
			{
				Toast.makeText(getApplicationContext(), getString(R.string.reproduct_format_error2), Toast.LENGTH_LONG).show();
			}
			rect.top = Integer.valueOf(values[0].trim());
			//Toast.makeText(getApplicationContext(), "getRectFromString top:" + rect.top, Toast.LENGTH_LONG).show();
			rect.bottom = Integer.valueOf(values[1].trim());
			//Toast.makeText(getApplicationContext(), "getRectFromString bottom:" + rect.bottom, Toast.LENGTH_LONG).show();
			rect.left = Integer.valueOf(values[2].trim());
			//Toast.makeText(getApplicationContext(), "getRectFromString left:" + rect.left, Toast.LENGTH_LONG).show();
			rect.right = Integer.valueOf(values[3].trim());
			//Toast.makeText(getApplicationContext(), "getRectFromString right:" + rect.right, Toast.LENGTH_LONG).show();
			Log.v("TVtool", " " + rect.top + " " + rect.bottom + " "
					+ rect.left + " " + rect.right);
		} catch (Exception e) {
			e.printStackTrace();
			Log.v("TVtool", "ini File format wrong");
			Toast.makeText(getApplicationContext(), getString(R.string.reproduct_divide_error) + e.toString(),
					Toast.LENGTH_LONG).show();
			return null;
		}
		return rect;
	}

	private boolean checkIniFileExists() {
		// TODO Auto-generated method stub
		File iniFile = new File(localIniFilePath);
		if (iniFile.exists()) {
			return true;
		}
		return false;
	}

	private void setIniFileNameAndPath() {
		// TODO Auto-generated method stub
//		iniFileName = productName + "_SC.ini";
//		localIniFilePath = "/hwcfg/overscan/" + iniFileName;
		iniFileName = "overscan.ini";
//		localIniFilePath = "/vendor/cusdata/apollo/common/overscan/" + iniFileName;
		localIniFilePath = Contants.FACTORY_TVTOOLS_OVERSCANPATH;
		sdcardIniFilePath = SDPath
				+ "/" + iniFileName;
	}

	private void getProductName() {
		// TODO Auto-generated method stub
		try {
			
			curTiming = MtkTvFApiInputSource.getInstance().getOverscanTimingByType(curSourceType);
			curScreenMode = MtkTvAVMode.getInstance().getScreenMode();
			String tempString = MtkTvFApiDisplay.getInstance().getPanelIni();
		    if (tempString != null || !tempString.isEmpty()) {
		    	productName = tempString.substring(tempString.lastIndexOf("/") + 1,
		                tempString.lastIndexOf("."));
		    } else {
		    	productName = MtkTvFApiDisplayIniManager.getInstance().getKey(MtkTvFApiDisplayIniManager.MTKTV_FAPI_KEY_TYPE_DISPLAY_ENUM.E_MTK_FAPI_KEY_TYPE_PANEL_NAME.ordinal());
		    }
			
			curSourceType = MtkTvFApiInputSource.getInstance().getCurrentInputSourceType();
			//less of MTK
//			productName = mTvMiscManager.getPanelName();
//			productName = TVManager.getInstance(ReproductionService.this)
//					.getMiscManager().getPanelName();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (productName == null || productName.isEmpty()) {
			productName = "UnkonwPanelName";
		}
		tv_panelName.setText(productName);
		setIniFileNameAndPath();// Set the INI file path and file name
	}

	public boolean setReproductionRateValue() {
		sb_top.setProgress(curRect.top);
		sb_bottom.setProgress(curRect.bottom);
		sb_left.setProgress(curRect.left);
		sb_right.setProgress(curRect.right);
		return true;
	}

	OnSeekBarChangeListener listener_seekBar = new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			// TODO Auto-generated method stub
			switch (seekBar.getId()) {
			case R.id.seekBar_top:
				curRect.top = progress;
				tv_top.setText(String.valueOf(progress));
				break;

			case R.id.seekBar_bottom:
				curRect.bottom = progress;
				tv_bottom.setText(String.valueOf(progress));
				/*
				 * try { TVManager.getInstance(ReproductionService.this)
				 * .getPictureManager().setToolCurOverScan(curRect); } catch
				 * (IllegalValueException e) { // TODO Auto-generated catch
				 * block e.printStackTrace(); } catch (TVManagerNotInitException
				 * e) { // TODO Auto-generated catch block e.printStackTrace();
				 * } Log.v(TAG, "bottom:" + Integer.toString(progress));
				 */
				break;

			case R.id.seekBar_left:
				curRect.left = progress;
				tv_left.setText(String.valueOf(progress));
				/*
				 * try { TVManager.getInstance(ReproductionService.this)
				 * .getPictureManager().setToolCurOverScan(curRect); } catch
				 * (IllegalValueException e) { // TODO Auto-generated catch
				 * block e.printStackTrace(); } catch (TVManagerNotInitException
				 * e) { // TODO Auto-generated catch block e.printStackTrace();
				 * } Log.v(TAG, "left:" + Integer.toString(progress));
				 */
				break;

			case R.id.seekBar_right:
				curRect.right = progress;
				tv_right.setText(String.valueOf(progress));
				/*
				 * try { TVManager.getInstance(ReproductionService.this)
				 * .getPictureManager().setToolCurOverScan(curRect); } catch
				 * (IllegalValueException e) { // TODO Auto-generated catch
				 * block e.printStackTrace(); } catch (TVManagerNotInitException
				 * e) { // TODO Auto-generated catch block e.printStackTrace();
				 * } Log.v(TAG, "right:" + Integer.toString(progress));
				 */
				break;
			default:
				break;
			}

			setOverScanValues(curIndex, curRect);
			try {
				//less of MTK
//				mTvMiscManager.setToolCurOverScan(curRect);
//				TVManager.getInstance(ReproductionService.this)
//						.getPictureManager().setToolCurOverScan(curRect);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			Log.v(TAG, "top:" + Integer.toString(progress));
		}
	};

	// The refresh will re read the screen name, reread the configurfation file, and retrieve the Index. The configuration file exists, but the format is wrong, and all data is set to default. The configuration file does not exist. Create a new one using the default value.
	private OnClickListener listener_btRefresh = new OnClickListener() {
		public void onClick(View v) {
			Log.v(TAG, "Refresh data!");

			getProductName();
			resetUI();

//			if (new File(localIniFilePath).exists()) {
//				if (!readIniFile()) {
//					resetOverScanValues();
//				}
//				refreshUI(getCurIndex());
//				Toast.makeText(getApplicationContext(), getString(R.string.reproduct_use_default_config),
//						Toast.LENGTH_SHORT).show();
//
//			} else {
//				Toast.makeText(getApplicationContext(),
//						getString(R.string.reproduct_no_config_file), Toast.LENGTH_LONG).show();
//				int i, j;
//				for (i = 0; i < overScanNames.length; i++) {
//					for (j = 0; j < 4; j++) {
//						overScanValues[i][j] = OVER_SCAN_VALUES[i][j];
//					}
//				}
//				createNewIniFile();
//				refreshUI(getCurIndex());
//			}
		}

	};

	/*
	 * Name: UI component tv_top, TV represents type, TextView. Underlined words followed by tables.
	 */
	private static final String TAG = "Reproduction";
	private static final int seekBarStep = 1;
	Rect curRect = null;
	int inittop = 0;
	int initbottom= 0;
	int initleft = 0;
	int initright = 0;
	SeekBar sb_top, sb_bottom, sb_left, sb_right;
	TextView tv_top, tv_bottom, tv_left, tv_right;
	Button bt_refresh, bt_exit, bt_save, bt_export;
	TextView tv_panelName, tv_indexName;
	boolean bSignal = true;
	boolean bOverScanModeHigh = false;
	boolean bUSBMode = false;
	int curIndex = 0;
	String productName, iniFileName, localIniFilePath, sdcardIniFilePath;
	String[] overScanNames = { "TV_PAL", "TV_PAL_M","TV_PAL_N","TV_NTSC", "TV_NTSC_443","TV_SECAM",

	"AV_PAL","AV_PAL_M","AV_PAL_N", "AV_NTSC_M","AV_NTSC_443", "AV_SECAM",

	"YPBPR_480I", "YPBPR_480P", "YPBPR_576I", "YPBPR_576P", "YPBPR_720P_50",
			"YPBPR_720P_60", "YPBPR_1080I_50", "YPBPR_1080I_60",
			"YPBPR_1080P_50", "YPBPR_1080P_60", "YPBPR_1080P_30",
			"YPBPR_1080P_24",

			"VGA_480I", "VGA_480P", "VGA_576I", "VGA_576P", "VGA_720P_50",
			"VGA_720P_60", "VGA_1080I_50", "VGA_1080I_60", "VGA_1080P_50",
			"VGA_1080P_60", "VGA_1080P_30", "VGA_1080P_24",

			"HDMI_480I", "HDMI_480P", "HDMI_576I", "HDMI_576P",
			"HDMI_1440_480I", "HDMI_1440_480P", "HDMI_1440_576I",
			"HDMI_1440_576P", "HDMI_720P_50", "HDMI_720P_60", "HDMI_1080I_50",
			"HDMI_1080I_60", "HDMI_1080P_50", "HDMI_1080P_60", "HDMI_1080P_30",
			"HDMI_1080P_24",

			"DTV_480I", "DTV_480P", "DTV_576I", "DTV_576P", "DTV_720P_50",
			"DTV_720P_60", "DTV_1080I_50", "DTV_1080I_60", "DTV_1080P_50",
			"DTV_1080P_60", "DTV_1080P_30", "DTV_1080P_24",
			
			"MMP_480I","MMP_480P","MMP_1080I_60","MMP_1080P_60",

			"NET_480I", "NET_480P", "NET_1080I_60", "NET_1080P_60",

			"IPTV_480I", "IPTV_480P", "IPTV_1080I_60", "IPTV_1080P_60",
			
			"SVIDEO_PAL", "SVIDEO_NTSC", "SVIDEO_SECAM",

			"OTHER_480I", "OTHER_480P", "OTHER_1080I_60", "OTHER_1080P_60",			

			"WITH_0"

	};

	final int[][] OVER_SCAN_VALUES = { 
			{ 310, 360, 470, 450 },{ 310, 360, 470, 450 },{ 310, 360, 470, 450 },
			{ 300, 260, 385, 370 },{ 300, 260, 385, 370 }, { 210, 290, 460, 450 },

			{ 300, 370, 500, 440 }, { 300, 370, 500, 440 },{ 300, 370, 500, 440 },{ 300, 290, 420, 400 },
			{ 300, 290, 420, 400 },{ 310, 370, 490, 440 },

			{ 180, 180, 200, 180 }, { 180, 200, 200, 200 },
			{ 200, 180, 210, 200 }, { 200, 180, 200, 200 },
			{ 200, 190, 190, 200 }, { 200, 190, 190, 200 },
			{ 190, 190, 190, 200 }, { 190, 190, 190, 200 },
			{ 200, 180, 190, 200 }, { 200, 180, 190, 200 },
			{ 200, 180, 190, 200 }, { 200, 180, 190, 200 },

			{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
			{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
			{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },

			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 190, 190, 190, 200 }, { 190, 190, 190, 200 },
			{ 200, 200, 190, 200 }, { 200, 200, 190, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },

			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },			

			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },

			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			
			{ 300, 370, 500, 440 }, { 300, 290, 420, 400 },
			{ 310, 370, 490, 440 },			

			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },
			{ 200, 200, 200, 200 }, { 200, 200, 200, 200 },

			{ 0, 0, 0, 0 }

	};

	int[][] overScanValues = new int[OVER_SCAN_VALUES.length][4];

	protected void resetOverScanValues() {
		// TODO Auto-generated method stub
		for (int i = 0; i < OVER_SCAN_VALUES.length; i++) {
			for (int j = 0; j < 4; j++) {
				overScanValues[i][j] = OVER_SCAN_VALUES[i][j];
			}
		}
	}
}// Service

